<script setup>
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  artAddService,
  artGetDetialService,
  artUpdateService
} from '@/api/article.js'
import { baseURL } from '@/utils/request.js'
import { imageUrlToFile } from '@/utils/format.js'
// 控制抽屉的显示隐藏
const visibalDrawer = ref(false)

const formRef = ref()
// 提供表单默认数据
const defaultState = {
  title: '', // 标题
  cate_id: '', // 文章分类id
  content: '', // 文章内容
  cover_img: '', //文章封面
  state: '' // 状态
}
const formState = ref({ ...defaultState }) // 将defaultState中的项展开

const rules = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  cate_id: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
  cover_img: [{ required: true, message: '请上传文章封面', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}

const imageUrl = ref('')
const onUpload = (uploadFile) => {
  //   console.log(uploadFile)
  imageUrl.value = URL.createObjectURL(uploadFile.raw) // 基于本地的图片显示图片
  formState.value.cover_img = uploadFile.raw
}

// open({}) => 添加操作
// opne({}) => 编辑操作
const editorRef = ref()
const open = async (row) => {
  visibalDrawer.value = true
  if (!row.id) {
    // 添加 → 重置数据
    formState.value = { ...defaultState }
    imageUrl.value = ''
    editorRef.value.setHTML('')
    console.log('添加操作')
  } else {
    // 编辑 → 回显数据
    const res = await artGetDetialService(row.id)
    formState.value = res.data.data
    // 图片需要单独处理 => 拼接服务器的基地址
    imageUrl.value = baseURL + formState.value.cover_img
    // 提交给后台的是 file 格式，需要将网络图片转换为 file 格式
    formState.value.cover_img = await imageUrlToFile(
      imageUrl.value,
      formState.value.cover_img
    )
  }
}

const emit = defineEmits(['success'])
const onPublish = async (state) => {
  formState.value.state = state
  // formState 普通对象 需要转成form-data对象
  const formdata = new FormData()
  for (let key in formState.value) {
    formdata.append(key, formState.value[key])
  }

  if (formState.value.id) {
    // 编辑操作
    await artUpdateService(formdata)
    ElMessage.success('修改成功')
    visibalDrawer.value = false
    emit('success', 'update')
  } else {
    // 添加操作
    await artAddService(formdata)
    ElMessage.success('添加成功')
    visibalDrawer.value = false
    // 告诉父组件，重新渲染数据
    emit('success', 'add')
  }
}

// 暴露open方法
defineExpose({
  open
})
</script>

<template>
  <!-- 抽屉 -->
  <el-drawer
    v-model="visibalDrawer"
    title="添加文章"
    direction="rtl"
    size="50%"
  >
    <el-form :model="formState" :rules="rules" ref="formRef">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formState.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <!-- 
            width="100%" 
            添加属性的方式 => 父传子
            需要在子组件中定义prop来接收父组件传来的参数，进行渲染
        -->
        <channel-select
          v-model:model-value="formState.cate_id"
          style="width: 100%"
        >
        </channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 使用upload组件 需要关闭自动上传, 手动处理处理图片的逻辑
             URL.createObjectURL(xxx)
        -->
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            ref="editorRef"
            them="snow"
            v-model:content="formState.content"
            content-type="html"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
